/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

#include "kernel_operator.h"
#include "lib/matmul_intf.h"
#include "../kernel_impl/matmul_async_custom_impl.h"
#include "testcase_params.h"

template <const ComputeMode mode>
__aicore__ inline constexpr AscendC::TPosition GetCPos()
{
    if constexpr (mode == ComputeMode::ITERATE_ALL) {
        // use IterateAll, only support CTYPE::TPosition is GM
        return AscendC::TPosition::GM;
    } else if constexpr (mode == ComputeMode::ITERATE) {
        // use Iterate, only support CTYPE::TPosition is VECIN
        return AscendC::TPosition::VECIN;
    }
    return AscendC::TPosition::GM;
}

__aicore__ inline void CopyTiling(TCubeTiling* tiling, GM_ADDR tilingGM)
{
    uint32_t* ptr = reinterpret_cast<uint32_t*>(tiling);
    auto tiling32 = reinterpret_cast<__gm__ uint32_t*>(tilingGM);

    for (int i = 0; i < sizeof(TCubeTiling) / sizeof(uint32_t); i++, ptr++) {
      *ptr = *(tiling32 + i);
    }
    return;
}

extern "C" __global__ __aicore__ void matmul_async_custom(const GM_ADDR a, const GM_ADDR b, const GM_ADDR c,
    const GM_ADDR workspace, const GM_ADDR tilingGm)
{
    TCubeTiling tiling;
    CopyTiling(&tiling, tilingGm);
    constexpr AscendC::TPosition cPos = GetCPos<TESTCASE_PARAMS.mode>();
    MatmulAsyncKernel<half, half, float, float, cPos> matmulAsyncKernel;
    AscendC::TPipe pipe;
    REGIST_MATMUL_OBJ(&pipe, GetSysWorkSpacePtr(), matmulAsyncKernel.matmulObj, &tiling);
    matmulAsyncKernel.Init(a, b, nullptr, c, workspace, tiling);
    matmulAsyncKernel.Process<TESTCASE_PARAMS.hasBias>(&pipe);
}

#ifndef ASCENDC_CPU_DEBUG
void matmul_async_custom_do(uint32_t blockDim, void* stream, GM_ADDR a, GM_ADDR b,
                    GM_ADDR c, GM_ADDR workspace, GM_ADDR tilingGm)
{
    matmul_async_custom<<<blockDim, nullptr, stream>>>(a, b, c, workspace, tilingGm);
}
#endif